import React, { useRef } from 'react'
import { message, Modal } from 'antd'
import PropTypes from 'prop-types'
import { CaseContext } from '../../../context'
import { addPartyRequest } from '../ajax/partyAjax'
import { awaitWrap } from '@js/tool'
import ModalForm from './ModalForm'

// 获取默认值
function getInitialValues (caseid, type, dictionaries) {
  const typeList = dictionaries['主体类型'] || []
  const subjectType = typeList[0] || {}
  const companyLicenseTypes = (dictionaries['企业证件类型'] || []).map(li => li.title)
  return {
    caseid,
    type,
    name: undefined, // 全称姓名
    subject_type: subjectType.value, // 主体类型（企业、自然人、非法人组织）
    subject_type_tag: subjectType.title, // 主体详细类型（如：国企）
    license_type: companyLicenseTypes[0] || '', // 证照类型
    license: undefined, // 证照号
    legal: undefined, // 法定代表人（自然人为空）
    address: undefined, // 详细住所
    area: '本地', // 区域信息（当事人所在地）
    mobile: undefined, // 手机号
    email: undefined, // 邮箱
    tel: undefined // 其他联系方式
  }
}

// 表单回调，提交数据
async function onFinish (data, caseid, type, list, callback, hide) {
  data.caseid = caseid
  data.type = type
  if (data.subject_type === '自然人') {
    data.legal = ''
  }
  data.license = data.license || ''
  const h = message.loading('提交中', 120)
  const [e, d] = await awaitWrap(addPartyRequest(data))
  h()
  if (e) {
    return message.warning(e.message)
  }
  const l = list ? [...list] : []
  l.push(d)
  callback(l)
  hide()
}

function Main ({ visible, type, hide, value, onChange }) {
  const formRef = useRef(null)
  return (
    <Modal
      width='700px'
      title={`新增${type}`}
      open={visible}
      onOk={() => formRef.current.submit()}
      onCancel={hide}
      maskClosable={false}
      destroyOnClose
    >
      <CaseContext.Consumer>
        {({ id, dictionaries, isPre }) => (
          <ModalForm ref={formRef} isPre={isPre} initialValues={getInitialValues(id, type, dictionaries)} dictionaries={dictionaries} onFinish={d => onFinish(d, id, type, value, onChange, hide)} />
        )}
      </CaseContext.Consumer>
    </Modal>
  )
}

Main.propTypes = {
  visible: PropTypes.bool,
  type: PropTypes.string,
  hide: PropTypes.func,
  value: PropTypes.array,
  onChange: PropTypes.func
}

Main.defaultProps = {
  visible: false,
  type: '',
  hide: () => {},
  value: [],
  onChange: () => {}
}

export default Main
